<template>
	<el-form @keyup.enter='loginByMoble(ruleFormRef)' ref="ruleFormRef" :model="ruleForm" :rules="rules"
		class="demo-ruleForm" status-icon size="large">
		<el-form-item prop="mobile">
			<el-input placeholder="手机号码" prefix-icon="iphone" v-model="ruleForm.mobile">
				<template #prepend>+86</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="captcha">
			<div style="display: flex; width: 100%;">
				<el-input placeholder="短信验证码" prefix-icon="lock" v-model="ruleForm.captcha"></el-input>
				<el-button @click="getCaptcha" :disabled="isDisabled" style="margin-left: 10px;">{{ $t('login.smsGet')
				}}<span v-if="isDisabled">{{ countdown
}}</span></el-button>
			</div>
		</el-form-item>
		<el-form-item>
			<el-button @click="loginByMoble(ruleFormRef)" round style="width: 100%;" :loading="isLoading">{{
				$t('login.signIn') }}</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts">
import { getSendRegisterOrLoginCaptchaAPI, postLoginByMobileAPI } from '@renderer/api/login';
import { useLogin } from '@renderer/composables/login';
import { mobileForm } from '@renderer/interface/login';
import { Encrypt } from '@renderer/utils/aes';
import { FormInstance } from 'element-plus';
import { computed, getCurrentInstance, reactive, ref } from 'vue';

// 倒计时
const countdown = ref(60)

// 表单验证
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<mobileForm>({
	mobile: '16684118533',
	captcha: ''
})
const { proxy } = getCurrentInstance()!
const rules = computed(() => {
	return {
		mobile: [
			{ required: true, pattern: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/, message: proxy?.$t('login.mobileError'), trigger: 'blur' }
		],
		captcha: [
			{ required: true, message: proxy?.$t('login.smsError'), trigger: 'blur' }
		],
	}
})

// 禁用获取验证码按钮
const isDisabled = ref(false)
// 标记定时器
let timer: NodeJS.Timeout
// 获取手机验证码
const getCaptcha = async () => {
	const validate = await ruleFormRef.value?.validateField('mobile', () => null)
	if (!validate) return
	getSendRegisterOrLoginCaptchaAPI(Encrypt(ruleForm.mobile))
	isDisabled.value = true
	timer = setInterval(() => {
		countdown.value--
		if (countdown.value === 0) {
			clearInterval(timer)
			isDisabled.value = false
			countdown.value = 60
		}
	}, 1000)
}

// 标记登录加载状态
const isLoading = ref(false)
// 登录
const loginByMoble = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate(async (valid) => {
		if (valid) {
			isLoading.value = true
			const res = await postLoginByMobileAPI({
				mobile: Encrypt(ruleForm.mobile),
				captcha: Encrypt(ruleForm.captcha)
			})

			// 获取 TOKEN 失败，退出
			if (res.code !== '200') {
				isLoading.value = false
				return
			}

			// 调用组合式函数
			useLogin(res)

			// 停止加载状态
			isLoading.value = false
		}
	})
}
</script>

<style scoped></style>@renderer/composables/useLogin